﻿using Microsoft.AspNetCore.Authorization;

namespace WebApplication1.Security
{
    public class RedisRoleAuthorizationHandler : AuthorizationHandler<RedisRoleAuthorizationRequirement>
    {

        private readonly RedisAuthUser _redisAuthUser;

        public RedisRoleAuthorizationHandler(RedisAuthUser redisAuthUser)
        {
            _redisAuthUser = redisAuthUser;
        }

        protected override Task HandleRequirementAsync(AuthorizationHandlerContext context, RedisRoleAuthorizationRequirement requirement)
        {
            if (_redisAuthUser.Roles == null) { 
                context.Fail();
                return Task.CompletedTask;
            }
            var found = _redisAuthUser.Roles!.Any(r => requirement.AllowRoles.Contains(r));
            if (found)
            {
                context.Succeed(requirement);
            }
            else
            {
                context.Fail();
            }
            return Task.CompletedTask;
        }
    }
    public class RedisRoleAuthorizationRequirement : IAuthorizationRequirement
    {
        public readonly List<string> AllowRoles;

        public RedisRoleAuthorizationRequirement(List<string> allowRoles)
        {
            AllowRoles = allowRoles;
        }
    }
}
